import axios from 'axios'
import { Message, Loading } from 'element-ui'
import store from '../store'
import { getToken } from './auth' // 获取到token
import { dateFormat } from './index'
import md5 from 'js-md5'

function isNumber(obj) {
  return typeof obj === 'number' && !isNaN(obj)
}

function isString(str) {
  return typeof str === 'string' && str.constructor == String
}

// 创建一个axios实例
const service = axios.create({
  // baseURL: process.env.NODE_ENV == 'development' ? 'http://backend-yz.3czu.cn' : '',
  baseURL: process.env.NODE_ENV == 'development' ? 'http://backend.njmaixi.cn' : '',
  timeout: 25000,
  headers: {
    'Content-Type': 'application/json;charset=utf-8'
  }
})

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    let isMini = false;
    let minicrypt = "";
    if(config.url.indexOf("Mini")!=-1){
      isMini = true;
      config.url = config.url.replace("/Mini","");
      // 解构赋值
      let {
        url = '',
        data = { timeStamp:+new Date() },
        params= { timeStamp:+new Date() },
        method = 'POST'
      } = { ...config };

      if(config.method == 'get' || config.method == 'get'){
        if(JSON.stringify(params) == JSON.stringify({})){
          params = { timeStamp:+new Date() }
        }
        for (let key in params) {
          params[key] += '';
        }
      }else{
        for (let key in data) {
          data[key] += '';
        }
      }
      // config.data = JSON.stringify(obj);
      const secretKey = 'sdksdksdcfsd'
      if(config.method == 'get' || config.method == 'get'){
        minicrypt = md5(JSON.stringify(params) + secretKey)
        config.params = params;
      }else{
        minicrypt = md5(JSON.stringify(data) + secretKey)
      }

      config.headers['crypt'] = minicrypt
      if(localStorage.getItem("token")){
        config.headers['token'] = localStorage.getItem("token")
      }
    }else{
      config.url = process.env.VUE_APP_BASE_API+config.url;
    }
    const secretKey = 'sdksdksdcfsd'
    const timeStamp = new Date().getTime() + ''
    let crypt = ''
    if (config.method === 'get') {
      config.params = config.params ? config.params : { timeStamp }
      for (const key in config.params) {
        config.params[key] =
          config.params[key] || config.params[key] === 0
            ? isNumber(config.params[key])
              ? config.params[key] + ''
              : config.params[key]
            : ''
        if (isString(config.params[key])) {
          config.params[key] = config.params[key].trim()
        }
      }
      crypt = md5(JSON.stringify(config.params) + secretKey)
    } else {
      if (config.url.indexOf('/Admin/upload')!=-1) {
        config.data.append('timeStamp', timeStamp)
        const params = {
          sizeLimit: config.data.get('sizeLimit'),
          riginalName: config.data.get('riginalName'),
          timeStamp
        }
        crypt = md5(JSON.stringify({ ...params }) + secretKey)
      } else {
        config.data =
          config.data && JSON.stringify(config.data) !== '{}'
            ? config.data
            : { timeStamp }
        for (const key in config.data) {
          config.data[key] =
            config.data[key] || config.data[key] === 0
              ? isNumber(config.data[key])
                ? config.data[key] + ''
                : config.data[key]
              : ''
          if (isString(config.data[key])) {
            config.data[key] = config.data[key].trim()
          }
        }
        crypt = md5(JSON.stringify(config.data) + secretKey)
      }
    }
    if(!isMini){
      config.headers['adminCrypt'] = crypt
    }

    const token = getToken() // 获取token
    if (token) {
      // 每次请求都需要带上token去请求接口
      config.headers['Authorization'] = token
    }
    config.headers['promoter-platform'] = store.state.setting.projectInfo.promoter_platform
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    if (response.status === 200) {
      if (response.data.status === 200) {
        return Promise.resolve(response.data)
      } else {
        Message.error(response.data.msg)
        if (response.data.status === 300) {
          store.dispatch('user/logout')
        }
        return Promise.reject(response)
      }
    } else {
      return Promise.reject(response)
    }
  },
  (error) => {
    switch (error.response.status) {
      case 405:
        Message.error(error.response.info)
        break
      default:
        break
    }
    return Promise.reject(error)
  }
)

export default {
  /**
   * get方法，对应get请求
   * @param {String} url [请求的url地址]
   * @param {Object} params [请求时携带的参数]
   * @param {Boolean} flag [是否弹出提示]
   */
  get(url, params, flag) {
    return new Promise((resolve, reject) => {
      service
        .get(url, {
          params: params
        })
        .then((res) => {
          if (flag && res.status === 200) {
            Message.success(res.msg)
          }
          resolve(res.data)
        })
        .catch((err) => {
          reject(err.data)
        })
    })
  },

  /**
   * post方法，对应post请求
   * @param {String} url [请求的url地址]
   * @param {Object} params [请求时携带的参数]
   * @param {Boolean} flag [是否弹出提示]
   */
  post(url, params, flag) {
    return new Promise((resolve, reject) => {
      service
        .post(url, params)
        .then((res) => {
          if (flag && res.status === 200) {
            Message.success(res.msg)
          }
          resolve(res.data)
        })
        .catch((err) => {
          reject(err.data)
        })
    })
  },
  /**
   * upload方法，对应upload post请求
   * @param {String} url [请求的url地址]
   * @param {Object} params [请求时携带的参数]
   * @param {Boolean} flag [是否弹出提示]
   */
  upload(url, params, flag) {
    return new Promise((resolve, reject) => {
      service
        .post(url, params, {
          headers: { 'Content-Type': 'multipart/form-data' }
        })
        .then((res) => {
          if (flag && res.status === 200) {
            Message.success(res.msg)
          }
          resolve(res.data)
        })
        .catch((err) => {
          reject(err.data)
        })
    })
  },
  /**
   * export方法
   * @param {String} url [请求的url地址]
   * @param {Object} params [请求时携带的参数]
   */
  export(url, params, name) {
    const loading = Loading.service({
      lock: true,
      text: '导出中。。。。。。',
      spinner: 'el-icon-loading'
    })
    return new Promise((resolve, reject) => {
      const secretKey = 'sdksdksdcfsd'
      const timeStamp = new Date().getTime() + ''
      const data =
        params && JSON.stringify(params) !== '{}' ? params : { timeStamp }
      for (const key in data) {
        data[key] =
          data[key] || data[key] === 0
            ? isNumber(data[key])
              ? data[key] + ''
              : data[key]
            : ''
        if (isString(data[key])) {
          data[key] = data[key].trim()
        }
      }
      const crypt = md5(JSON.stringify(data) + secretKey)
      axios
        .post(process.env.VUE_APP_BASE_API + url, data, {
          responseType: 'blob',
          headers: {
            'Content-Type': 'application/json',
            Authorization: getToken(),
            adminCrypt: crypt
          }
        })
        .then((res) => {
          const link = document.createElement('a')
          const blob = new Blob([res.data], {
            type: 'application/vnd.ms-excel'
          })
          link.style.display = 'none'
          link.href = URL.createObjectURL(blob)
          link.download = name + dateFormat(new Date()) + '.xls'
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
          loading.close()
          resolve(true)
        })
        .catch((err) => {
          loading.close()
          reject(err)
        })
    })
  }
}
